{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "FItt1ZfwlnIi"
   },
   "source": [
    "# 循环神经网络的从零开始实现\n",
    "\n",
    "在本节中，我们将从零开始实现一个基于字符级循环神经网络的语言模型，并在周杰伦专辑歌词数据集上训练一个模型来进行歌词创作。首先，我们读取周杰伦专辑歌词数据集："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "vRhoZLAhlntp"
   },
   "outputs": [],
   "source": [
    "import d2ltorch as d2lt\n",
    "import math\n",
    "import torch\n",
    "from torch import nn\n",
    "import time\n",
    "\n",
    "(corpus_indices, char_to_idx, idx_to_char, \n",
    " vocab_size) = d2lt.load_data_jay_lyrics()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "ALrqAs8Kms4w"
   },
   "source": [
    "## one-hot向量\n",
    "\n",
    "为了将词表示成向量输入到神经网络，一个简单的办法是使用one-hot向量。假设词典中不同字符的数量为$N$（即词典大小`vocab_size`），每个字符已经同一个从0到$N-1$的连续整数值索引一一对应。如果一个字符的索引是整数$i$, 那么我们创建一个全0的长为$N$的向量，并将其位置为$i$的元素设成1。该向量就是对原字符的one-hot向量。下面分别展示了索引为0和2的one-hot向量，向量长度等于词典大小。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 52
    },
    "colab_type": "code",
    "id": "amctN_fHmtm4",
    "outputId": "6580d7d3-e1b1-4eb8-c327-78f0fffe145d"
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[1., 0., 0.,  ..., 0., 0., 0.],\n",
       "        [0., 0., 1.,  ..., 0., 0., 0.]])"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def one_hot(idx, size, device='cpu'): # 本函数已保存在d2ltorch包中方便以后使用\n",
    "    batch_size = idx.size(0)\n",
    "    index = idx.reshape(-1, 1)\n",
    "    return torch.zeros(batch_size, size).to(device).scatter_(dim=1, index=index, value=1)\n",
    "\n",
    "one_hot(torch.LongTensor([0, 2]), vocab_size)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "nlDhbO0imw1m"
   },
   "source": [
    "我们每次采样的小批量的形状是(批量大小, 时间步数)。下面的函数将这样的小批量变换成数个可以输入进网络的形状为(批量大小, 词典大小)的矩阵，矩阵个数等于时间步数。也就是说，时间步$t$的输入为$\\boldsymbol{X}_t \\in \\mathbb{R}^{n \\times d}$，其中$n$为批量大小，$d$为输入个数，即one-hot向量长度（词典大小）。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 35
    },
    "colab_type": "code",
    "id": "YQoxkBFVmzBK",
    "outputId": "d664bd96-1a68-41f2-cd4f-34eaf04f0361"
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(5, torch.Size([2, 1027]))"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def to_onehot(X, size, device='cpu'): # 本函数已保存在d2ltorch包中方便以后使用\n",
    "    return [one_hot(x, size, device) for x in X.long().t()]\n",
    "\n",
    "X = torch.arange(10).reshape(2, 5)\n",
    "inputs = to_onehot(X, vocab_size)\n",
    "len(inputs), inputs[0].shape"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "hqfozfRem2az"
   },
   "source": [
    "## 初始化模型参数\n",
    "\n",
    "接下来，我们初始化模型参数。隐藏单元个数 `num_hiddens`是一个超参数。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 35
    },
    "colab_type": "code",
    "id": "xNuP1GBtm4KP",
    "outputId": "d6776ec6-a926-4493-c49c-eb84e548e10f"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "will use cuda:0\n"
     ]
    }
   ],
   "source": [
    "num_inputs, num_hiddens, num_outputs = vocab_size, 256, vocab_size\n",
    "device = d2lt.try_gpu()\n",
    "print('will use', device)\n",
    "\n",
    "def get_params():\n",
    "    def _one(shape):\n",
    "        return torch.normal(mean=torch.zeros(shape), std=0.01).to(device)\n",
    "    \n",
    "    # 隐藏层参数\n",
    "    W_xh = _one((num_inputs, num_hiddens))\n",
    "    W_hh = _one((num_hiddens, num_hiddens))\n",
    "    b_h = torch.zeros(num_hiddens).to(device)\n",
    "    # 输出层参数\n",
    "    W_hq = _one((num_hiddens, num_outputs))\n",
    "    b_q = torch.zeros(num_outputs).to(device)\n",
    "    # 附上梯度\n",
    "    params = [W_xh, W_hh, b_h, W_hq, b_q]\n",
    "    \n",
    "    for param in params:\n",
    "        param.requires_grad = True\n",
    "    return params"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "rCp9_O9cm6xP"
   },
   "source": [
    "## 定义模型\n",
    "\n",
    "我们根据循环神经网络的计算表达式实现该模型。首先定义`init_rnn_state`函数来返回初始化的隐藏状态。它返回由一个形状为(批量大小, 隐藏单元个数)的值为0的`Tensor`组成的元组。使用元组是为了更便于处理隐藏状态含有多个`Tensor`的情况。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "LsP6XZaBm86B"
   },
   "outputs": [],
   "source": [
    "def init_rnn_state(batch_size, num_hiddens, device):\n",
    "    return (torch.zeros(batch_size, num_hiddens).to(device), )"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "ZA31X904m_ap"
   },
   "source": [
    "下面的`rnn`函数定义了在一个时间步里如何计算隐藏状态和输出。这里的激活函数使用了tanh函数。[“多层感知机”](../chapter_deep-learning-basics/mlp.ipynb)一节中介绍过，当元素在实数域上均匀分布时，tanh函数值的均值为0。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "7BmrsuoznBZ6"
   },
   "outputs": [],
   "source": [
    "def rnn(inputs, state, params):\n",
    "    # inputs和outputs皆为num_steps个形状为(batch_size, vocab_size)的矩阵\n",
    "    W_xh, W_hh, b_h, W_hq, b_q = params\n",
    "    H, = state\n",
    "    outputs = []\n",
    "    for X in inputs:\n",
    "        H = torch.tanh(X.mm(W_xh) + H.mm(W_hh) + b_h)\n",
    "        Y = H.mm(W_hq) + b_q\n",
    "        outputs.append(Y)\n",
    "    return outputs, (H,)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "bPVaBDwCnDZi"
   },
   "source": [
    "做个简单的测试来观察输出结果的个数（时间步数），以及第一个时间步的输出层输出的形状和隐藏状态的形状。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 35
    },
    "colab_type": "code",
    "id": "t3y93Hp8nFRE",
    "outputId": "d3b9a459-b16e-49de-b4d7-5249382877a3"
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(5, torch.Size([2, 1027]), torch.Size([2, 256]))"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "state = init_rnn_state(X.shape[0], num_hiddens, device)\n",
    "inputs = to_onehot(X.to(device), vocab_size, device)\n",
    "params = get_params()\n",
    "outputs, state_new = rnn(inputs, state, params)\n",
    "len(outputs), outputs[0].shape, state_new[0].shape"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "T2kMXtx1ozGi"
   },
   "source": [
    "## 定义预测函数\n",
    "\n",
    "以下函数基于前缀`prefix`（含有数个字符的字符串）来预测接下来的`num_chars`个字符。这个函数稍显复杂，其中我们将循环神经单元`rnn`设置成了函数参数，这样在后面小节介绍其他循环神经网络时能重复使用这个函数。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "JCWJqDgao1KW"
   },
   "outputs": [],
   "source": [
    "# 本函数已保存在d2ltorch包中方便以后使用\n",
    "def predict_rnn(prefix, num_chars, rnn, params, init_rnn_state,\n",
    "               num_hiddens, vocab_size, device, idx_to_char, char_to_idx):\n",
    "    state = init_rnn_state(1, num_hiddens, device)\n",
    "    output = [char_to_idx[prefix[0]]]\n",
    "    with torch.no_grad():\n",
    "        for t in range(num_chars + len(prefix) - 1):\n",
    "            # 将上一时间片的输出作为当前时间步的输入\n",
    "            X = to_onehot(torch.Tensor([[output[-1]]]).to(device), vocab_size, device)\n",
    "            # 计算输出和更新隐藏状态\n",
    "            (Y, state) = rnn(X, state, params)\n",
    "            # 下一个时间步的输入是prefix里的字符或者当前的最佳预测字符\n",
    "            if t < len(prefix) - 1:\n",
    "                output.append(char_to_idx[prefix[t + 1]])\n",
    "            else:\n",
    "                output.append(int(Y[0].argmax(dim=1).item()))\n",
    "    return ''.join([idx_to_char[i] for i in output])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "a3RtdedNqovn"
   },
   "source": [
    "我们先测试一下`predict_rnn`函数。我们将根据前缀“分开”创作长度为10个字符（不考虑前缀长度）的一段歌词。因为模型参数为随机值，所以预测结果也是随机的。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 35
    },
    "colab_type": "code",
    "id": "wqkV13zgrWPP",
    "outputId": "f63aa380-a792-4656-e5da-bcf06016b92e"
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'分开恩病古打翔沟朵危丘办'"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "predict_rnn('分开', 10, rnn, params, init_rnn_state, num_hiddens, vocab_size,\n",
    "           device, idx_to_char, char_to_idx)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "w_iJ04TUranw"
   },
   "source": [
    "## 裁剪梯度\n",
    "\n",
    "循环神经网络中较容易出现梯度衰减或梯度爆炸。我们会在[“通过时间反向传播”](bptt.ipynb)一节中解释原因。为了应对梯度爆炸，我们可以裁剪梯度（clip gradient）。假设我们把所有模型参数梯度的元素拼接成一个向量 $\\boldsymbol{g}$，并设裁剪的阈值是$\\theta$。裁剪后的梯度\n",
    "\n",
    "$$ \\min\\left(\\frac{\\theta}{\\|\\boldsymbol{g}\\|}, 1\\right)\\boldsymbol{g}$$\n",
    "\n",
    "的$L_2$范数不超过$\\theta$。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "1QspVp-krcWd"
   },
   "outputs": [],
   "source": [
    "# 本函数已保存在d2ltorch包中方便以后使用\n",
    "def grad_clipping(params, theta, device):\n",
    "    norm = torch.Tensor([0]).to(device)\n",
    "    for param in params:\n",
    "        norm += (param.grad.data ** 2).sum()\n",
    "    norm = norm.sqrt().item()\n",
    "    if norm > theta:\n",
    "        for param in params:\n",
    "            param.grad.data.mul_(theta / norm)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "cXFqw27krgO-"
   },
   "source": [
    "## 困惑度\n",
    "\n",
    "我们通常使用困惑度（perplexity）来评价语言模型的好坏。回忆一下[“softmax回归”](../chapter_deep-learning-basics/softmax-regression.ipynb)一节中交叉熵损失函数的定义。困惑度是对交叉熵损失函数做指数运算后得到的值。特别地，\n",
    "\n",
    "* 最佳情况下，模型总是把标签类别的概率预测为1，此时困惑度为1；\n",
    "* 最坏情况下，模型总是把标签类别的概率预测为0，此时困惑度为正无穷；\n",
    "* 基线情况下，模型总是预测所有类别的概率都相同，此时困惑度为类别个数。\n",
    "\n",
    "显然，任何一个有效模型的困惑度必须小于类别个数。在本例中，困惑度必须小于词典大小`vocab_size`。\n",
    "\n",
    "## 定义模型训练函数\n",
    "\n",
    "跟之前章节的模型训练函数相比，这里的模型训练函数有以下几点不同：\n",
    "\n",
    "1. 使用困惑度评价模型。\n",
    "2. 在迭代模型参数前裁剪梯度。\n",
    "3. 对时序数据采用不同采样方法将导致隐藏状态初始化的不同。相关讨论可参考[“语言模型数据集（周杰伦专辑歌词）”](lang-model-dataset.ipynb)一节。\n",
    "\n",
    "另外，考虑到后面将介绍的其他循环神经网络，为了更通用，这里的函数实现更长一些。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "qNfl3KPjrjC9"
   },
   "outputs": [],
   "source": [
    "# 本函数已保存在d2ltorch包中方便以后使用\n",
    "def train_and_predict_rnn(rnn, get_params, init_rnn_state, num_hiddens,\n",
    "                          vocab_size, device, corpus_indices, idx_to_char,\n",
    "                          char_to_idx, is_random_iter, num_epochs, num_steps,\n",
    "                          lr, clipping_theta, batch_size, pred_period,\n",
    "                          pred_len, prefixes):\n",
    "    if is_random_iter:\n",
    "        data_iter_fn = d2lt.data_iter_random\n",
    "    else:\n",
    "        data_iter_fn = d2lt.data_iter_consecutive\n",
    "    params = get_params()\n",
    "    loss = nn.CrossEntropyLoss()\n",
    "    \n",
    "    for epoch in range(num_epochs):\n",
    "        if not is_random_iter: # 如使用相邻采样，在epoch开始时初始化隐藏状态\n",
    "            state = init_rnn_state(batch_size, num_hiddens, device)\n",
    "        l_sum, n, start = 0.0, 0, time.time()\n",
    "        data_iter = data_iter_fn(corpus_indices, batch_size, num_steps, device)\n",
    "        for X, Y in data_iter:\n",
    "            if is_random_iter:  # 如使用随机采样，在每个小批量更新前初始化隐藏状态\n",
    "                state = init_rnn_state(batch_size, num_hiddens, device)\n",
    "            else:  # 否则需要使用detach函数从计算图分离隐藏状态\n",
    "                for s in state:\n",
    "                    s.detach_()\n",
    " \n",
    "            inputs = to_onehot(X, vocab_size, device)\n",
    "            # outputs有num_steps个形状为(batch_size, vocab_size)的矩阵\n",
    "            (outputs, state) = rnn(inputs, state, params)\n",
    "            # 拼接之后形状为(num_steps * batch_size, vocab_size)\n",
    "            outputs = torch.cat(outputs, dim=0)\n",
    "            # Y的形状是(batch_size, num_steps)，转置后再变成长度为\n",
    "            # batch_size * num_steps 的向量，这样跟输出的行一一对应\n",
    "            y = Y.t().flatten().long()\n",
    "            \n",
    "            # 使用交叉熵损失计算平均分类误差\n",
    "            l = loss(outputs, y).mean()\n",
    "            l.backward()\n",
    "            grad_clipping(params, clipping_theta, device)  # 裁剪梯度\n",
    "            d2lt.sgd(params, lr, 1)  # 因为误差已经取过均值，梯度不用再做平均\n",
    "            l_sum += l.data.item() * torch.numel(y.data)\n",
    "            n += torch.numel(y.data)\n",
    "            \n",
    "        if (epoch + 1) % pred_period == 0:\n",
    "            print('epoch %d, perplexity %f, time %.2f sec' % (\n",
    "                epoch + 1, math.exp(l_sum / n), time.time() - start))\n",
    "            for prefix in prefixes:\n",
    "                print(' -', predict_rnn(\n",
    "                    prefix, pred_len, rnn, params, init_rnn_state,\n",
    "                    num_hiddens, vocab_size, device, idx_to_char, char_to_idx))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "KGp5lTmhsOP7"
   },
   "source": [
    "## 训练模型并创作歌词\n",
    "\n",
    "现在我们可以训练模型了。首先，设置模型超参数。我们将根据前缀“分开”和“不分开”分别创作长度为50个字符（不考虑前缀长度）的一段歌词。我们每过50个迭代周期便根据当前训练的模型创作一段歌词。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "Tnt6BC0ssQka"
   },
   "outputs": [],
   "source": [
    "num_epochs, num_steps, batch_size, lr, clipping_theta = 250, 35, 32, 1e2, 1e-2\n",
    "pred_period, pred_len, prefixes = 50, 50, ['分开', '不分开']"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "HFCiM69esSio"
   },
   "source": [
    "下面采用随机采样训练模型并创作歌词。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 297
    },
    "colab_type": "code",
    "id": "NgfhJhsKsU_e",
    "outputId": "bfbce56d-d9a5-461c-a785-a89b0d788457"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 50, perplexity 71.102366, time 0.30 sec\n",
      " - 分开 我想想这 我 想这你 别子的美 全有了这 我颗我这 我想想这 我想想这 我有我这 我想想这 我有我\n",
      " - 不分开 快颗去我 你的手空 我想我这多  后 我有你的可爱 我有你这 我想想这 我有我这 我想想这 我有我\n",
      "epoch 100, perplexity 10.258602, time 0.30 sec\n",
      " - 分开 有使用 一步两 三颗四 干什么 干什么 干什么 干什么 干什么 干什么 干什么 干什么 干什么 干\n",
      " - 不分开柳 我不要再想你 不知不觉 你已经 不么我 娘子就 干什么 干什么 一九四 一颗的让我心红的可爱女人\n",
      "epoch 150, perplexity 2.849834, time 0.30 sec\n",
      " - 分开 不想了你 全成之空 我一定纵 恨真的让 你已放头 我让后知不要再 牵着你 手 我对儿有 不亮我不见\n",
      " - 不分开吗 我叫好爸 你知我妈 这样的从蜜 用制茶 一果空 装属我抬脚这开 但使用  我的 爸有时间 全小放\n",
      "epoch 200, perplexity 1.603830, time 0.29 sec\n",
      " - 分开 一直会停留 谁让它 一句惹毛我的人有危险 一再重演千年的誓言 一切又重演 祭司 神殿 征战 弓箭 \n",
      " - 不分开期 我叫你爸 你打我妈 这样对空 你一种空 说我不懂 说了没用 他的感容 还一秒钟 不敢不同 你已懂\n",
      "epoch 250, perplexity 1.299777, time 0.32 sec\n",
      " - 分开 一直令你 心成了容  一直 废不风不 快使用双截棍 哼哼哈兮 快使用双截棍 哼 我用手刀防飞  说\n",
      " - 不分开扫把的胖女巫 用拉丁文念咒语啦啦呜 她养的黑猫笑起来像哭 啦啦啦呜 它想我回见 让静我习著够  你去\n"
     ]
    }
   ],
   "source": [
    "train_and_predict_rnn(rnn, get_params, init_rnn_state, num_hiddens,\n",
    "                      vocab_size, device, corpus_indices, idx_to_char,\n",
    "                      char_to_idx, True, num_epochs, num_steps, lr,\n",
    "                      clipping_theta, batch_size, pred_period, pred_len,\n",
    "                      prefixes)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "CT4-uhd9tX6V"
   },
   "source": [
    "接下来采用相邻采样训练模型并创作歌词。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 297
    },
    "colab_type": "code",
    "id": "h5BMi_QWtZyB",
    "outputId": "b6cc45be-ed60-400d-a3f5-b3fdfee2e60a"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 50, perplexity 63.158961, time 0.28 sec\n",
      " - 分开 我想要这 你谁我有 不要我有 不要我有 不天我有 不要我有 不要我有 不要我有 不天我有 不要我有\n",
      " - 不分开 我不要这 不果我有 快谁我有 不要我有 快谁我有 不要我有 不天我有 不要我有 不要我有 不天我有\n",
      "epoch 100, perplexity 7.104511, time 0.30 sec\n",
      " - 分开 我说要这生活 我该你好生活 不知不觉 快天用沙凉过 一北的客栈人多 牧草有没有 我马儿有些瘦 我不\n",
      " - 不分开难爱 我想要你的微笑有天都能看到  我知道这里很美但家乡的你更美 刻能来暴 在谁的脚 在人己梦 你一\n",
      "epoch 150, perplexity 2.055035, time 0.29 sec\n",
      " - 分开 这说的话去还水 是一枝人 温亮是有 在红海中 你在没空 恨我不懂 在我没中 在了没真 你不放 连一\n",
      " - 不分开觉 就已经离开我 不知不觉 我跟了这节奏 后知后觉 又过了一个秋 后知后觉 我该好好生活 我该好好生\n",
      "epoch 200, perplexity 1.277912, time 0.30 sec\n",
      " - 分开 我说能 生九走睛年着 有话人看着我 抛物线进球 单手过人运球 篮下妙传出手 漂亮的假动作 帅呆了我\n",
      " - 不分开觉远就多 我想有没有坦堡 就像是童话故事  有教堂有城堡 每天忙碌地的寻找 到底什么我想要 却发现迷\n",
      "epoch 250, perplexity 1.147400, time 0.30 sec\n",
      " - 分开 问候是人子的慢白 古堡金酒三点阳光 他们儿子我习惯 从小现迷了路怎么 也是开了了口斯B难过 印地安\n",
      " - 不分开觉远你多 我想你没斯坦着道 什么我都做得到 但那个人已经不是我 上海一九四三 泛黄的春联还残 我来有\n"
     ]
    }
   ],
   "source": [
    "train_and_predict_rnn(rnn, get_params, init_rnn_state, num_hiddens,\n",
    "                      vocab_size, device, corpus_indices, idx_to_char,\n",
    "                      char_to_idx, False, num_epochs, num_steps, lr,\n",
    "                      clipping_theta, batch_size, pred_period, pred_len,\n",
    "                      prefixes)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "Vo6oG1fSuYDN"
   },
   "source": [
    "## 小结\n",
    "\n",
    "* 可以用基于字符级循环神经网络的语言模型来生成文本序列，例如创作歌词。\n",
    "* 当训练循环神经网络时，为了应对梯度爆炸，可以裁剪梯度。\n",
    "* 困惑度是对交叉熵损失函数做指数运算后得到的值。\n",
    "\n",
    "\n",
    "## 练习\n",
    "\n",
    "* 调调超参数，观察并分析对运行时间、困惑度以及创作歌词的结果造成的影响。\n",
    "* 不裁剪梯度，运行本节中的代码，结果会怎样？\n",
    "* 将`pred_period`变量设为1，观察未充分训练的模型（困惑度高）是如何创作歌词的。你获得了什么启发？\n",
    "* 将相邻采样改为不从计算图分离隐藏状态，运行时间有没有变化？\n",
    "* 将本节中使用的激活函数替换成ReLU，重复本节的实验。\n",
    "\n",
    "\n",
    "\n",
    "## 扫码直达[讨论区](https://discuss.gluon.ai/t/topic/989)\n",
    "\n",
    "![](../img/qr_rnn-scratch.svg)"
   ]
  }
 ],
 "metadata": {
  "accelerator": "GPU",
  "colab": {
   "collapsed_sections": [],
   "name": "rnn-scratch.ipynb",
   "provenance": [],
   "version": "0.3.2"
  },
  "kernelspec": {
   "display_name": "Python [conda env:pytorch]",
   "language": "python",
   "name": "conda-env-pytorch-py"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.9"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
